﻿#include "InpKeyLineSpliter.h"
#include "InpKeyWordsChecker.h"
#include "FITKAbaqusINPReader.h"

namespace IO
{

    InpKeyLineSpliter::InpKeyLineSpliter(const QString& line, FITKAbaqusINPReader* readerInp)
        :_line(line),_reader(readerInp)
    {
        //构造初始化并处理字符串数据
        initProcessed(line);
    }

    QString InpKeyLineSpliter::getHeader()
    {
        return _header;
    }

    int InpKeyLineSpliter::count()
    {
        return _keys.size();
    }

    QString InpKeyLineSpliter::getKeyIndex(int index)
    {
        if (index >= count() || index < 0) return QString();
        return _keys.at(index);
    }

    QString InpKeyLineSpliter::operator[](const QString& key)
    {
        //不区分大小写，全部转换为小写
        QString lkey = key.toLower();
        if (_keyValues.contains(lkey))
            return _keyValues.value(lkey);
        return QString();
    }

    bool InpKeyLineSpliter::hasValue(const QString& key)
    {
        //不区分大小写，全部转换为小写
        QString lkey = key.toLower();
        return _keyValues.contains(lkey);
    }

    bool InpKeyLineSpliter::hasKey(const QString& key)
    {
        return _keys.contains(key) ;
    }

    void InpKeyLineSpliter::reset(const QString& aline)
    {
        //清空重置
        _line = _header = "";
        _keys.clear();
        _keyValues.clear();

        _line = aline;
        initProcessed(aline);
    }

    void InpKeyLineSpliter::initProcessed(QString line)
    {
        //移除字符 *
        if (!line.startsWith("*") || line.startsWith("**")) return;
        line.remove('*');
        line = line.simplified();
        QStringList strList = line.split(',');

        //解析头
        if (strList.size() < 1) return;
        _header = strList.at(0).simplified();

        for (int i = 1; i < strList.size(); ++i)
        {
            const QString currentStr = strList.at(i);

            //不包含等于号的处理
            if (!currentStr.contains("="))
            {
                _keys.append(currentStr.simplified());
                continue;
            }

            QStringList key_value = strList.at(i).split('=');
            if (key_value.size() != 2) continue;
            //包含等于号的需要解析value
            const QString k = key_value.at(0).simplified();
            const QString v = key_value.at(1).simplified();

            _keys.append(k);
            _keyValues.insert(k, v);
        }

        if(_reader)
            _reader->checkKeyWords(_header, _keys, _keyValues);

    }

}

